package com.example.actordemo3.sharding;

import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.cluster.sharding.ClusterSharding;
import akka.cluster.sharding.ClusterShardingSettings;
import akka.cluster.sharding.ShardRegion;

public class CluterPer extends AbstractActor {
   static ShardRegion.MessageExtractor messageExtractor = new ShardRegion.MessageExtractor() {
        @Override
        public String shardId(Object message) {
            int numberOfShards = 100;
            if (message instanceof ShardingTest.Counter.EntityEnvelope) {
                long id = ((ShardingTest.Counter.EntityEnvelope) message).id;
                return String.valueOf(id % numberOfShards);
            } else if (message instanceof ShardingTest.Counter.Get) {
                long id = ((ShardingTest.Counter.Get) message).counterId;
                return String.valueOf(id % numberOfShards);
            } else {
                return null;
            }
        }

        @Override
        public String entityId(Object message) {
            if (message instanceof ShardingTest.Counter.EntityEnvelope)
                return String.valueOf(((ShardingTest.Counter.EntityEnvelope) message).id);
            else if (message instanceof ShardingTest.Counter.Get)
                return String.valueOf(((ShardingTest.Counter.Get) message).counterId);
            else return null;
        }

        @Override
        public Object entityMessage(Object message) {
            if (message instanceof ShardingTest.Counter.EntityEnvelope)
                return ((ShardingTest.Counter.EntityEnvelope) message).payload;
            else return message;
        }
    };


    @Override
    public void preStart() throws Exception {
        System.out.println("开始");
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder().build();
    }

    public static void main(String[] args) {

        ActorSystem system = ActorSystem.create("sys1");
        ActorRef actorRef = system.actorOf(Props.create(CluterPer.class), "cluterPer");
//        ClusterShardingSettings settings = ClusterShardingSettings.create(system);
//        ActorRef startedCounterRegion =
//                ClusterSharding.get(system)
//                        .start("CluterPer", Props.create(CluterPer.class), settings,messageExtractor );
//        ActorRef counterRegion = ClusterSharding.get(system).shardRegion("cluterPer");
//
//        System.out.println("111");
    }
}
